<?php
namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use com\gdl\newagk\interfaces\QbankPracticeServiceClient;
use com\gdl\newagk\dataobject\qbankpractice\QbankDTO;
use com\gdl\newagk\dataobject\qbankpractice\QbankQuestionDTO; 

/**
 * App题库练习相关接口
 * 包含 错题 练习记录
 */

class QbankPractice extends Base
{
	/**
	 * 添加做题记录
	 */
	public function setQbankQuestion(){
		$msg = ['code'=>400, 'msg'=>'添加做题记录失败','data'=>[]];
		$praformId = $this->request->param("parform_id") ? $this->request->param("parform_id") : ""; # 平台id
		$identityId = $this->request->param("identityId") ? $this->request->param("identityId"):""; # 用户id
		$qbankId = $this->request->param("qbankId") ? $this->request->param("qbankId"):""; # 题库id
		$typeId = $this->request->param("typeId") ? $this->request->param("typeId") : ""; # 题型id
		$questionId = $this->request->param("questionId") ? $this->request->param("questionId") :"";
		$knowId = $this->request->param("knowId") ? $this->request->param("knowId"):"";
		$judge = $this->request->param('judge') ? $this->request->param("judge"):"0"; # 1对 0错 2未知
		$type = $this->request->param('type') ? $this->request->param('type'):"order"; # * special：专项练习 * error :错题练习 * collection: 收藏
		if(empty($identityId) || empty($questionId)){
			$msg['msg'] = "缺少必要参数";
			return json_encode($msg);
		}
		if($judge==0||empty($judge)){
			$judge = 0;
		}

		try{

			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $praformId;
            $QbankDO->identity_id = $identityId;
            $QbankDO->data = ['plaformId'=>$praformId,'identityId'=>$identityId,'qbankId'=>$qbankId,'typeId'=>$typeId, 'type'=>$type,'questionId'=>$questionId,'knowId'=>$knowId,'judge'=>$judge,'createTime'=>time()];
            $result = $api->setQbankQuestion($QbankDO);

            if($result->success ==true){
            	$msg['code'] = $result->code;
            	$msg['msg'] = $result->message;
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 专项练习标签接口 第一个
	 */
	public function specialTagList(){
		$msg = ['code'=>400, 'msg'=>'获取失败','data'=>[]];
		$qbankId = $this->request->param("qbankId") ? $this->request->param("qbankId") : "";
		$identityId = $this->request->param("identityId") ? $this->request->param("identityId") : "";
		if(empty($qbankId)){
			$msg['msg'] = "请选择题库";
			return json_encode($msg);
		}
		if(empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $qbankId;
            $QbankDO->identity_id = $identityId;
            $result = $api->specialTagList($QbankDO); 
            if($result->success ==true){
            	$msg['code'] = $result->code;
            	$msg['msg'] = $result->message;
            	if($result->code ==200){
            		$msg['data'] = json_decode($result->data[0]['data']);
            	}
            	
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 公共题库标签赛选接口
	 */
	public function qbankTagList(){
		$msg = ['code'=>400,'msg'=>'获取失败','data'=>[]];
		$qbankId = $this->request->param('qbankId') ? $this->request->param('qbankId'):"";
		$identityId = $this->request->param('identityId')?$this->request->param('identityId'):"";

		if(empty($qbankId)){
			$msg['msg'] = "请选择题库";
			return json_encode($msg);
		}
		if(empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $qbankId;
            $QbankDO->identity_id = $identityId;
            $result = $api->qbankTagList($QbankDO); 
            if($result->success==true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = $result->code;
            	if($result->code==200){
            		$msg['data'] = json_decode($result->data[0]['data']);
            	}
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}

		return json_encode($msg);
	}
	/**
	 * 错题题库列表接口
	 */
	public function errorQbankList(){
		$msg = ['code'=>400,'msg'=>'暂无错题','data'=>[]];
		$plafromId = $this->request->param("plafromId")?$this->request->param("plafromId"):"";
		$identityId = $this->request->param("identityId")?$this->request->param("identityId"):"";
		$offset = $this->request->param("page")?$this->request->param("page"):1;
		$num = $this->request->param("pagesize")?$this->request->param("pagesize"):10;

		if(empty($plafromId) || empty($identityId)){
			$msg['msg'] = "请先登录";
			// return json_encode($msg);
		}
		# 获取该平台下子平台和当前平台的数据
        $adminReg = getApiAdminReg($plafromId,'one');
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $plafromId;
            $QbankDO->filed = $adminReg;
            $QbankDO->offset=$offset;
            $QbankDO->num = 10;
            $QbankDO->identity_id = $identityId;
            $result = $api->errorQbankList($QbankDO);
            if($result->success == true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = $result->code;
            	if($result->code==200){
            		$msg['data'] = $result->data;
            	}
            } 
		}catch(Exception $e){
			$msg['msg']= $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 我的收藏题库列表
	 */
	public function collectionQbankList(){
		$msg = ['code'=>400,'msg'=>'暂无错题','data'=>[]];
		$plafromId = $this->request->param("plafromId")?$this->request->param("plafromId"):"";
		$identityId = $this->request->param("identityId")?$this->request->param("identityId"):"";
		$offset = $this->request->param("page")?$this->request->param("page"):1;
		$num = $this->request->param("pagesize")?$this->request->param("pagesize"):10;

		if(empty($plafromId) || empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		# 获取该平台下子平台和当前平台的数据
        $adminReg = getApiAdminReg($plafromId,'one');
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $plafromId;
            $QbankDO->filed = $adminReg;
            $QbankDO->offset=$offset;
            $QbankDO->num = 10;
            $QbankDO->identity_id = $identityId;
            $result = $api->collectionQbankList($QbankDO);
            if($result->success == true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = $result->code;
            	if($result->code==200){
            		$msg['data'] = $result->data;
            	}
            } 
		}catch(Exception $e){
			$msg['msg']= $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 该题库你做了多少题
	 */
	public function getQbankNum(){
		$msg = ['code'=>200,'msg'=>'暂无数据','data'=>[]];
		$qbankId = $this->request->param("qbankId")?$this->request->param("qbankId"):"";	
		$identityId = $this->request->param("identityId")?$this->request->param("identityId"):"";
		if(empty($qbankId)||empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $qbankId;  
            $QbankDO->identity_id = $identityId;
            $result = $api->getQbankNum($QbankDO);
            if($result->success==true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = 200;
            	if($result->code==200){
            		$msg['data'] = json_decode($result->data[0]['data']);
            	}
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 收藏/取消收藏
	 */
	public function setCollection(){
		$msg = ['code'=>400,'msg'=>'设置失败','data'=>[]];
		$plafromId = $this->request->param("plafromId") ? $this->request->param("plafromId"):"";
		$qbankId = $this->request->param("qbankId") ? $this->request->param("qbankId"): "";
		$identityId = $this->request->param("identityId") ? $this->request->param("identityId"):"";
		$questionId = $this->request->param("questionId") ? $this->request->param("questionId") :"";
		$type = $this->request->param("type") ? $this->request->param("type") :"set"; # set：设置 del：取消收藏
		if(empty($plafromId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $plafromId;  
            $QbankDO->filed = $qbankId;  
            $QbankDO->identity_id = $identityId;
            $QbankDO->update = $questionId;
            $QbankDO->where = $type;
            $result = $api->setCollection($QbankDO);
            if($result->success == true){
            	$msg['code'] = $result->code;
            	$msg['msg'] = $result->message;
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 移除错题
	 */
	public function deleteError(){
		$msg = ['code'=>400,'msg'=>'您已移除错题，请勿重复操作','data'=>[]];
		$plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId"):"";
		$questionId = $this->request->param("questionId") ? $this->request->param("questionId"):"";
		$identityId = $this->request->param("identityId") ? $this->request->param("identityId"):"";
		if(empty($questionId) || empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api);
            $QbankDO = new QbankDTO();
            $QbankDO->id = $plaformId;   
            $QbankDO->identity_id = $identityId;
            $QbankDO->update = $questionId; 
            $result = $api->deleteError($QbankDO);
            if($result->success==true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = $result->code;
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 统一抽提接口
	 * order：顺序练习获取该题库下所有试题
	 * special：专项练习 根据选择试题种类 下属章节获取试题
	 * error :错题练习 查询当前题库下我的所有试题
	 * collection: 收藏，查询我当前收藏下的所有试题
	 */
	public function getQuestionList(){
		$msg = ['code'=>400,'msg'=>'抽提异常','data'=>[]];
		$plafromId = $this->request->param("plafromId") ? $this->request->param("plafromId") : 0;
		$att = $this->request->param("att") ? $this->request->param("att") : "order";
		# 顺序练习
		$qbankId = $this->request->param("qbankId") ? $this->request->param("qbankId"):"";
		# 专项练习选择试题类型
		$typeId = $this->request->param("typeId") ? $this->request->param("typeId"):"";
		# 专项练习选择试题章节
		$sectionId = $this->request->param("sectionId") ? $this->request->param("sectionId"):"";
		# 我的错题 我的收藏
		$identityId = $this->request->param("identityId") ? $this->request->param("identityId"):"";

		#赛选值
		$se_typeId = $this->request->param("se_typeId") ? $this->request->param("se_typeId"):"";
		$se_sectionId = $this->request->param("se_sectionId") ? $this->request->param("se_sectionId"):"";
		$se_tag = $this->request->param("se_tag") ?  $this->request->param("se_tag") : ""; # 标签pid 如果选了子分类则不传选了所有传123逗号分隔
        $se_tagVal = $this->request->param("se_tagVal") ?  $this->request->param("se_tagVal") : ""; # 标签值 子分类123逗号分隔
        // var_dump($identityId);
		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $api = new QbankPracticeServiceClient(NULL);
            \ApiClient::build($api); 
            $QbankDO = new QbankQuestionDTO();
            $QbankDO->praformid = $praformId;   
            $QbankDO->identity_id = $identityId;
            $QbankDO->att = $att;
            $QbankDO->qbankid=$qbankId;
            $QbankDO->sectionid=$sectionId;
            $QbankDO->typeid=$typeId; 

            $QbankDO->str1=$se_typeId; 
            $QbankDO->str2=$se_sectionId; 
            $QbankDO->str3=$se_tag; 
            $QbankDO->str4=$se_tagVal; 
            // var_dump($QbankDO);
            // var_dump($api);exit;
            $result = $api->getQuestionList($QbankDO); 
            if($result->success==true){
            	$msg['msg'] = $result->message;
            	$msg['code'] = $result->code;
            	if($result->code==200){
            		$msg['data'] = json_decode($result->message,true);
            		$msg['msg'] = "抽题成功";
            	}
            }
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 添加书签
	 */
	public function addBookMark(){
		$msg = ['code'=>400,'msg'=>'添加书签失败','data'=>[]];
		$qbankId = $this->request->param('qbankId') ? $this->request->param('qbankId'):"";
		$identityId = $this->request->param('identityId') ? $this->request->param('identityId'):"";
		$type = $this->request->param('type') ? $this->request->param('type'):"order"; #order:顺序special：专项练习error :错题练习collection: 收藏
		$id = $this->request->param('questionId') ? $this->request->param('questionId'):"";

		try{
			$where['qbankId'] = $qbankId;
			$where['identityId'] = $identityId;
			$where['isdelete'] = 0;
			$where['type']  = $type;
			# 查询练习id
			// var_dump($this->request->post());die;
			// $t = Db::name('testPaper')->where($where)->field("*")->find();
			// var_dump($t);die;
			$testPaper = Db::name('testPaper')->where($where)->setField(['bookMark'=>$id]);
			if($testPaper){
				$msg['msg'] = '已添加书签';
				$msg['code'] = 200;
			}
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 书签记录
	 */
	public function selectBookMark(){
		$msg = ['code'=>400,'msg'=>'未找到上次答题记录','data'=>[]];
		$qbankId = $this->request->param('qbankId') ? $this->request->param('qbankId'):"";
		$identityId = $this->request->param('identityId') ? $this->request->param('identityId'):"";
		$type = $this->request->param('type') ? $this->request->param('type'):"order"; #order:顺序special：专项练习error :错题练习collection: 收藏

		try{
			$where['qbankId'] = $qbankId;
			$where['identityId'] = $identityId;
			$where['isdelete'] = 0;
			$where['type']  = $type;
			# 查询练习id
			$testPaper = Db::name('testPaper')->where($where)->field('id,bookMark')->find();


			if($testPaper){
				$msg['msg'] = '已获取书签';
				$msg['code'] = 200;
				$msg['data'] = ['questionId'=>$testPaper['bookMark']?$testPaper['bookMark']:0];
			}
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 答题卡
	 */
	public function answerCard(){
		$msg = ['code'=>400,'msg'=>'获取答题卡失败','data'=>[]];
		$qbankId = $this->request->param('qbankId') ? $this->request->param('qbankId'):"";
		$identityId = $this->request->param('identityId') ? $this->request->param('identityId'):"";
		$type = $this->request->param('type') ? $this->request->param('type'):"order"; # 

		try{
			$where['qbankId'] = $qbankId;
			$where['identityId'] = $identityId;
			$where['isdelete'] = 0;
			$where['type']  = $type;
			# 查询练习id
			$testPaper = Db::name('testPaper')->where($where)->field('id,qbankId,quesId,type,identityId,isdelete')->find();
			$quesId = unserialize($testPaper['quesId'])?unserialize($testPaper['quesId']):[]; # 所有试题
			# 把试题的题型查出来
			$quesWhere['id']= ['in',$quesId];
			$quesWhere['isdelete'] = 0;
			$quesWhere['status'] = 1;
			$quesTypeList = Db::name('questions')->where($quesWhere)->field("id,typeId")->order('id desc')->select(); 
			#再查所有练习题
			$maps['isdelete'] = 0;
			$maps['qbankId'] = $qbankId;
			$maps['identityId'] = $identityId;
			#order:顺序special：专项练习error :错题练习collection: 收藏
			if($type=='collection'){
				$maps['type'] = $type;
			}
			if($type=='order'||$type=='special'){
				$maps['type'] = ['in',['order','special']];
			}
			$quesList = Db::name('pracitice')->where($maps)->field('*')->limit('id asc')->select(); # 做题记录
			$types= ['1'=>'single','2'=>'more','3'=>'judge','4'=>'gapFilling','5'=>'subjectivity'];
			// $types= ['1'=>'single','2'=>'more','3'=>'judge','4'=>'subjectivity','5'=>'gapFilling']; 
			 # 读错题表
			 if($type=='error'){ 
			 	$map['isdelete'] = 0;
				$map['qbankId'] = $qbankId;
				$map['identityId'] = $identityId;
			 	$quesList = Db::name('error_pracitice')->where($map)->field("*")->limit('id asc')->select();
			 }
			if($quesTypeList){
				$newCard = [];
				for($i=0; $i<count($quesTypeList); $i++){ 
					 $newCard[$types[$quesTypeList[$i]['typeId']]][$i] = ['0'=>$quesTypeList[$i]['id'],'1'=>0,'2'=>0]; #未作答 未知
					for($j=0;$j<count($quesList); $j++){
						if($quesTypeList[$i]['id']==$quesList[$j]['questionId']){
							# 其他
							if($type!='error'){
								$newCard[$types[$quesTypeList[$i]['typeId']]][$i] = [$quesTypeList[$i]['id'],'1'=>1,'2'=>intval($quesList[$j]['judge'])];	
							}
							# 错题
							if($type=='error'){
								$knows = 0;
								if(trim($quesList[$j]['knowId'])!="" && $quesList[$j]['knowId']!=" "){
									$knows = 1;
								}
								$newCard[$types[$quesTypeList[$i]['typeId']]][$i] = [$quesTypeList[$i]['id'],'1'=>$knows,'2'=>intval($quesList[$j]['judge'])];	
							}

						}
					}
				}
			}
			$resultArray = [];
			$i=0;
			$orderBy = 1;
			foreach ($types as $key) {
				$strs =  $this->emptyAnswer($newCard[$key],$orderBy);
				$resultArray[$i]['key'] = $key; 
				$resultArray[$i]['list'] = $this->eachStr($strs); 
				$orderBy+=count($this->eachStr($strs));
				$i++;
			}  
			$msg['code'] = 200;
			$msg['msg'] = "获取答题卡成功";
			$msg['data'] = $resultArray; 
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	public function eachStr($str){
		$res = [];
		foreach ($str as $key => $value) {
			$res[] = ['qid'=>$value['qid'],'selected'=>$value['selected'],'id'=>$value['id']];
		}
		return $res;
	}
	// 去重复值
	public function emptyAnswer($arr = array(),$count){
		$restulArray = [];
		$i=0;
		$order = $count;
		foreach ($arr as $key => $value) {  
			if($value[1]==1){ # 做了=1 没做0  作对2 做错3 未知4
				if($value[2]==1){
					$resultArray[$i] = ['qid'=>$value['0'],'selected'=>2,'id'=>$order];
				}else if($value[2]==0){
					$resultArray[$i] = ['qid'=>$value['0'],'selected'=>3,'id'=>$order];
				}else if($value[2]==2){
					$resultArray[$i] = ['qid'=>$value['0'],'selected'=>4,'id'=>$order];
					#做题记录 如果为3则为未知
				}else{
					$resultArray[$i] = ['qid'=>$value['0'],'selected'=>4,'id'=>$order];
				}
				
			}else{
				$resultArray[$i] = ['qid'=>$value['0'],'selected'=>$value['1'],'id'=>$order];
			} 
			$i++;
			$order++;
		}    
		 //var_dump($resultArray);die;
		return $resultArray;
	}
	/**
	 * 	清空练习记录
	 */
	public function deleteQuestionList(){
		$msg = ['code'=>400,'msg'=>'没有练习记录','data'=>[]];
		$qbankId = $this->request->param('qbankId') ? $this->request->param('qbankId'):"";
		$identityId = $this->request->param('identityId') ? $this->request->param('identityId'):"";
		$type = $this->request->param('type') ? $this->request->param('type'):"order"; # 备用字段
		if(empty($qbankId)){
			$msg['msg'] = "请选择题库";
			return json_encode($msg);
		}
		if(empty($identityId)){
			$msg['msg'] = "请先登录";
			return json_encode($msg);
		}
		try{
			#再查所有练习题
			$map['isdelete'] = 0;
			$map['qbankId'] = $qbankId;
			$map['identityId'] = $identityId;

			if($type=='error'){
				$errorQuesRet = Db::name('error_pracitice')->where($map)->setField(['knowId'=>" ",'judge'=>" "]); # 同时删除错题记录		
			}else{
				$map['type'] = $type;
				if($type=='order'){
					$map['type'] =  ['in','order,special'];
				}
				# 后面可以把顺序的记录删除
				if($type=='special'){
					//$map['type'] = 'special'; 
					$map['type'] =  ['in','order,special'];
				}
				$quesList = Db::name('pracitice')->where($map)->delete();//setField(['isdelete'=>1]); # 做题记录	
			}
			#顺便清空书签
			$where['qbankId'] = $qbankId;
			$where['identityId'] = $identityId;
			$where['isdelete'] = 0;
			$where['type']  = $type;
			$testPaper = Db::name('testPaper')->where($where)->setField(['bookMark'=>0]);
			if($quesList || $errorQuesRet){
				$msg['code'] = 200;
				$msg['msg'] = "清空做题记录成功";	
			}
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	/**
	 * 排序
	 */
	public function sortMax($arr){
		$resultArray = [];
		$len = count($arr);
		for($i=1;$i<$len;$i++){
		    for($k=0;$k<$len-$i;$k++){
		       if($arr[$k]['qid']<$arr[$k+1]['qid'])
		        {
		            $tmp=$arr[$k+1];
		            $arr[$k+1]=$arr[$k];
		            $arr[$k]=$tmp;
		        }
		    } 
		}
		return $arr;
	}
}